package com.heima.leadnews.publish.task;

import com.heima.feign.wemedia.WeMediaFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojo.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Component
@Slf4j
public class PublishWmNewsTaskRedis {

    @Autowired
    private WeMediaFeign wemediaFeign;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 延迟文章发布，基于redis实现
     * 定时任务，从零秒开始，每十秒执行一次定时任务
     */

    @Scheduled(cron = "0 0 * * * ?  ")
    @GlobalTransactional
    public void publish() {
        log.info("Redis的定时任务执行了...");
        Set<String> ids = redisTemplate.opsForZSet().rangeByScore("wmnews", 0, System.currentTimeMillis());
        if (ids != null && !ids.isEmpty()) {
            for (String id : ids) {
                ResponseResult<WmNews> responseResult = wemediaFeign.getNewsId(Integer.valueOf(id));
                if (responseResult.getCode() == AppHttpCodeEnum.SUCCESS.getCode()) {
                    //2.远程调用wedia微服务，发布文章，
                    WmNews wmNews = responseResult.getData();
                    //文章审核通过后，可以被修改
                    if (wmNews.getStatus() == WmNews.Status.APPROVED && wmNews.getPublishTime().before(new Date())) {
                        wemediaFeign.publish(wmNews);
                    }
                    redisTemplate.opsForZSet().remove("wmnews", id);
                }
            }
        }
    }
}
